package com.xbongbong.pro.message.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushSetEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.wrap.Entity;
import com.xbongbong.pro.message.constant.MessageSetDetailTitleConstants;
import com.xbongbong.pro.message.enums.PushObjectTypeEnum;
import com.xbongbong.pro.message.enums.PushParentTypeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.MessageSetDetailPojo;
import com.xbongbong.pro.message.pojo.dto.MessageSetDetailDTO;
import com.xbongbong.pro.message.pojo.vo.MessageSetDetailVO;
import com.xbongbong.pro.message.pojo.vo.PushSetVO;
import com.xbongbong.pro.message.pushset.DistributorCommunicatePushSet;
import com.xbongbong.pro.message.pushset.DistributorContactPushSet;
import com.xbongbong.pro.message.pushset.DistributorPushSet;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.DistributorCommunicateEnum;
import com.xbongbong.saas.enums.business.DistributorContactEnum;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 经销商消息推送设置
 *
 * @author LiZhikang
 * @date 2022/11/5 17:16
 */
@Service
public class DistributorMessageSetServiceImpl extends AbstractMessageSetService {

    @Resource
    private CustomerUserModel customerUserModel;


    @Override
    public List<String> alias() {
        return Collections.singletonList(XbbRefTypeEnum.DISTRIBUTOR.getAlias());
    }

    @Override
    public String initSetDetailList() throws Exception {
        return null;
    }

    @Override
    public MessageSetDetailVO getSetDetailList(MessageSetDetailDTO messageSetDetailDTO) throws Exception {
        List<MessageSetDetailPojo> messageSetDetailPojos = new ArrayList<>();
        Integer typeInt = messageSetDetailDTO.getSaasIds().get(0).intValue();
        typeInt = XbbRefTypeEnum.transferBusinessType4Distributor(typeInt, messageSetDetailDTO.getDistributorMark());
        String alias = PushTypeEnum.getByCode(typeInt).getAlias();
        if (!Objects.equals(alias, PushTypeEnum.UNKNOWN.getAlias())) {
            String methodName = "getMessageSetSaas" + alias.substring(0, 1).toUpperCase() + alias.substring(1) + "DetailList";
            Method method = this.getClass().getDeclaredMethod(methodName, String.class, List.class, Integer.class);
            method.invoke(this, messageSetDetailDTO.getCorpid(), messageSetDetailPojos, typeInt);
        }
        return new MessageSetDetailVO(messageSetDetailPojos);
    }

    /**
     * 经销商 9501
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    @Deprecated
    private void getMessageSetSaasDistributorPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> baseTypeEnum = new ArrayList<>();
        List<PushTypeEnum> otherTypeEnum = new ArrayList<>();
        pushTypeEnumList.forEach(pushTypeEnum -> {
            Integer subCode = pushTypeEnum.getSubCode();
            if (Objects.equals(subCode, PushTypeEnum.DISTRIBUTOR_ADD_PUSH.getSubCode())) {
                baseTypeEnum.add(pushTypeEnum);
            }
            if (Objects.equals(subCode, PushTypeEnum.DISTRIBUTOR_HANDOVER_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.DISTRIBUTOR_TEAM_ADD_DEL_MAIN.getSubCode()) || Objects.equals(subCode, PushTypeEnum.DISTRIBUTOR_TEAM_ADD_DEL_SYNERGETIC.getSubCode())) {
                otherTypeEnum.add(pushTypeEnum);
            }
        });

        List<PushSetEntity> basePushTypeList = new ArrayList<PushSetEntity>() {{
            baseTypeEnum.forEach(pushTypeEnum -> {
                add(new DistributorPushSet().getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel));
            });
        }};

        MessageSetDetailPojo baseDetail = new MessageSetDetailPojo() {{
            setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.DISTRIBUTOR_BASE));
            setValue(new ArrayList<PushSetVO>() {{
                BeanUtil.copyPropertiesList(basePushTypeList, this, PushSetVO.class);
            }});
        }};
        messageSetDetailPojos.add(baseDetail);

        List<PushSetEntity> otherPushTypeList = new ArrayList<PushSetEntity>() {{
            otherTypeEnum.forEach(pushTypeEnum -> {
                add(new DistributorPushSet().getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel));
            });
        }};
        MessageSetDetailPojo otherDetail = new MessageSetDetailPojo() {{
            setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.DISTRIBUTOR_FOLLOW));
            setValue(new ArrayList<PushSetVO>() {{
                BeanUtil.copyPropertiesList(otherPushTypeList, this, PushSetVO.class);
            }});
        }};
        messageSetDetailPojos.add(otherDetail);
    }

    /**
     * 经销商联系人 9502
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasDistributorContactPushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {

        List<PushTypeEnum> basePushTypeEnum = new ArrayList<PushTypeEnum>() {{
            new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt)).forEach(pushTypeEnum -> {
                if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.DISTRIBUTOR_CONTACT_ADD_PUSH.getSubCode())) {
                    add(pushTypeEnum);
                }
            });
        }};

        List<PushSetEntity> basePushTypeList = new ArrayList<PushSetEntity>() {{
            basePushTypeEnum.forEach(pushTypeEnum -> {
                add(new DistributorContactPushSet().getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel));
            });
        }};


        MessageSetDetailPojo baseDetail = new MessageSetDetailPojo() {{
            setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.DISTRIBUTOR_CONTACT_BASE));
            setValue(new ArrayList<PushSetVO>() {{
                BeanUtil.copyPropertiesList(basePushTypeList, this, PushSetVO.class);
            }});
        }};

        messageSetDetailPojos.add(baseDetail);
    }

    /**
     * 经销商跟进记录 9503
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasDistributorCommunicatePushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> basePushTypeEnum = new ArrayList<PushTypeEnum>() {{
            new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt)).forEach(pushTypeEnum -> {
                if (Objects.equals(pushTypeEnum.getSubCode(), PushTypeEnum.DISTRIBUTOR_COMMUNICATE_ADD_PUSH.getSubCode())) {
                    add(pushTypeEnum);
                }
            });
        }};

        List<PushSetEntity> basePushTypeList = new ArrayList<PushSetEntity>() {{
            basePushTypeEnum.forEach(pushTypeEnum -> {
                add(new DistributorCommunicatePushSet().getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel));
            });
        }};

        MessageSetDetailPojo detailPojo = new MessageSetDetailPojo() {{
            setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.DISTRIBUTOR_COMMUNICATE_BASE));
            setValue(new ArrayList<PushSetVO>() {{
                BeanUtil.copyPropertiesList(basePushTypeList, this, PushSetVO.class);
            }});
        }};

        messageSetDetailPojos.add(detailPojo);
    }


    @Override
    public List<String> getUserIdListByPushSetRule(String corpid, Integer type, Integer subType, UserEntity userEntity, Entity entity) throws Exception{
        String alias = PushParentTypeEnum.getByCode(type).getAlias();
        String methodName = "get" + alias.substring(0, 1).toUpperCase() + alias.substring(1) + "UserIdList";
        Method method = this.getClass().getDeclaredMethod(methodName, String.class, Integer.class, UserEntity.class, Entity.class);
        Object userIds = method.invoke(this, corpid, subType, userEntity, entity);
        return distinct(userIds);
    }

    /**
     * 经销商 9501
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getDistributorManagementUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> userIdList = new HashSet<>();
        CustomerEntityExt customerEntity = (CustomerEntityExt) entity;
        Long customerId = customerEntity.getId();
        DistributorPushSet distributorPushSet = new DistributorPushSet();
        PushSetEntity pushSetEntity = distributorPushSet.getPushSet(corpid, subType, pushSetModel);

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (customerId != null && customerId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            userIdList.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            userIdList.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(userIdList), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(userIdList), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 经销商联系人 9502
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getDistributorContactUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> result = new HashSet<>();
        ContactEntityExt contactEntity = (ContactEntityExt) entity;

        JSONObject dataObject = JsonHelperUtil.getJSONObject(contactEntity.getData());
        Long customerId = dataObject.getLong(DistributorContactEnum.DISTRIBUTOR_NAME.getAttr());
        DistributorContactPushSet distributorContactPushSet = new DistributorContactPushSet();
        PushSetEntity pushSetEntity = distributorContactPushSet.getPushSet(corpid, subType, pushSetModel);

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            //只有新数据
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");

            if (customerId != null && customerId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 经销商跟进记录 9503
     * @param corpid
     * @param subType
     * @param userEntity
     * @param entity
     * @return
     */
    private List<String> getDistributorCommunicateUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        //跟进记录
        String pushObjectString;
        Set<String> result = new HashSet<>();
        CustomerCommunicateEntityExt customerCommunicateEntity = (CustomerCommunicateEntityExt) entity;
        DistributorCommunicatePushSet distributorCommunicatePushSet = new DistributorCommunicatePushSet();
        PushSetEntity pushSetEntity = distributorCommunicatePushSet.getPushSet(corpid, subType, pushSetModel);
        JSONObject dataObject = JsonHelperUtil.getJSONObject(customerCommunicateEntity.getData());
        Long customerId = dataObject.getLong(DistributorCommunicateEnum.DISTRIBUTOR_NAME.getAttr());

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (customerId != null && customerId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 1));
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            result.addAll(customerUserModel.getCustomerUserIdList(corpid, Collections.singletonList(customerId), 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(result), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }

/*    if (Objects.equals(PushTypeEnum.DISTRIBUTOR_PUSH.getCode(), type)) {
        userIds = getDistributorManagementUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.DISTRIBUTOR_CONTACT_ADD_PUSH.getCode(), type)) {
        userIds = getDistributorContactUserIdList(corpid, subType, userEntity, entity);
    } else if (Objects.equals(PushTypeEnum.DISTRIBUTOR_COMMUNICATE_ADD_PUSH.getCode(), type)) {
        userIds = getDistributorCommunicateUserIdList(corpid, subType, userEntity, entity);
    }*/
}
